package com.lunchEveryDay.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

/**
 * Created by Admin on 2015/7/21.
 */
public class BaseDao<T,PK extends Serializable> {
	@Resource
	private SessionFactory sessionFactory;
	protected Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
			  .getActualTypeArguments()[0];

	public Session getCurrentSession(){
		return sessionFactory.getCurrentSession();
	}
	public T get(PK id) {
		T load = (T) this.getCurrentSession().get(entityClass,id);
		return load;
	}
	public void save(T t) {
		this.getCurrentSession().save(t);
	}
	public void saveOrUpdate(T t)	{
		this.getCurrentSession().saveOrUpdate(t);
	}
	public void update(T e) {
		getCurrentSession().update(e);
	}
	public void delete(T t)	{
		this.getCurrentSession().delete(t);
	}
	public java.util.List<T> listAll() {
		Query query = getCurrentSession().createQuery("FROM "+entityClass.getName());
		return query.list();
	}
	public boolean deleteById(PK id) {
		T t = get(id);
		if (t == null) {
			return false;
		}
		delete(t);
		return true;
	}
}